<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>加密解密工具（3.4.7.20250817.release）</title>
    <style>

        /* 版本水印样式 */
        .version-watermark {
            white-space: pre-line; /* 保留空白符（包括\n）的换行效果 */
            position: fixed;
            top: 5%;
            left: 42%;
            display: flex;
            justify-content: center; /* 水平居中 */
            transform: translateX(-50%);
            font-size: 120px;
            font-weight: bold;
            color: #ff55ff;
            opacity: 0.23;
            pointer-events: none; /* 让水印不影响下方元素的交互 */
            z-index: 9999; /* 确保水印在最上层 */
            user-select: none; /* 禁止选中水印文本 */
            text-align: center;
        }

        .container {
            width: 95%;
            max-width: 1400px;
            margin: 30px auto;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }

        .main-content {
            flex: 1;
            min-width: 500px;
            position: relative; /* 用于定位导航点 */
        }

        .side-content {
            width: 400px;
            min-width: 300px;
        }
        .tool-section {
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            position: relative;
        }
        .input-group {
            margin: 15px 0;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
            gap: 10px;
        }
        .range-inputs {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        select, input[type="text"], input[type="number"], textarea, button {
            padding: 10px 15px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        textarea {
            width: 100%;
            box-sizing: border-box;
        }
        .hidden {
            display: none;
        }
        .output-box {
            width: 100%;
            min-height: 220px;
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: none;
            font-size: 14px;
            line-height: 1.5;
        }
        .brute-force-results {
            width: 100%;
            min-height: 300px;
            margin-top: 15px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-align: left;
            font-size: 14px;
            line-height: 1.6;
            overflow-y: auto;
        }
        .result-item {
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px dashed #eee;
        }
        .result-item.highlight {
            background-color: #f8fff8;
            padding: 8px;
            border-radius: 4px;
            border-left: 3px solid #4CAF50;
        }
        .secondary-result {
            margin-top: 10px;
            padding: 10px;
            background-color: #f0f7ff;
            border-radius: 4px;
            font-size: 13px;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s, transform 0.2s;
        }
        button:hover {
            background-color: #45a049;
            transform: translateY(-1px);
        }
        button.secondary {
            background-color: #4CAF50;
        }
        button.secondary:hover {
            background-color: #45a049;
        }
        button.tertiary {
            background-color: #ff9800;
            padding: 5px 10px;
            font-size: 14px;
        }
        button.tertiary:hover {
            background-color: #e68900;
        }
        .note {
            color: #666;
            font-size: 14px;
            margin-top: 20px;
            text-align: left;
            padding: 0 10px;
        }
        .info {
            color: #444;
            font-size: 13px;
            margin-top: 5px;
        }
        .success {
            color: #2e7d32;
            font-size: 13px;
        }
        .error {
            color: #c62828;
            font-size: 13px;
        }
        .section-title {
            color: #333;
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
            margin-bottom: 20px;
            text-align: left;
        }
        .decrypt-mode-switch {
            margin-bottom: 20px;
            padding: 10px;
            background-color: #f5f5f5;
            border-radius: 4px;
        }
        .warning {
            color: #e74c3c;
            font-size: 13px;
            margin-top: 5px;
        }
        .utf16-tool {
            /* 移除置顶样式 */
        }

        /* 优化的页面引导导航样式 - 紧凑且固定位置 */
        .page-guide {
            position: fixed;
            left: calc(50% + 700px + 20px); /* 主内容区右侧20px */
            top: 60px; /* 距离顶部60px，保持置顶 */
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 40px; /* 间距适中，总计长度约等于一个工具框 */
            padding: 10px 0;
        }
        
        /* 针对不同屏幕尺寸的响应式调整 */
        @media (max-width: 1500px) {
            .page-guide {
                left: calc(50% + (100vw - 1400px)/2 + 700px + 20px);
            }
        }
        
        @media (max-width: 1400px) {
            .page-guide {
                left: calc(100% - 50px);
            }
        }
        
        .guide-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: #999;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            box-shadow: 0 0 0 2px rgba(255,255,255,0.8);
        }
        
        .guide-dot::after {
            content: attr(data-label);
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            white-space: nowrap;
            background-color: rgba(0,0,0,0.8);
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s;
        }
        
        .guide-dot:hover::after {
            opacity: 1;
        }
        
        .guide-dot.active {
            background-color: #2196F3;
            width: 16px;
            height: 16px;
            box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.3);
        }

        /* 平滑滚动 */
        html {
            scroll-behavior: smooth;
        }

        /* 工具区域的ID标识，用于导航定位 */
        #encrypt-tool, #decrypt-tool, #utf16-tool {
            scroll-margin-top: 50px;
        }
    </style>
</head>
<body>
    <!-- 版本水印 - 文本形式，便于后期修改 -->
    <div class="version-watermark">V3.4.7···V3.4.7
V3.4.7
V3.4.7·V3.4.7
V3.4.7
V3.4.7

</div>


    <!-- 页面引导导航 -->
    <div class="page-guide">
        <div class="guide-dot active" data-target="encrypt-tool" data-label="加密工具"></div>
        <div class="guide-dot" data-target="decrypt-tool" data-label="解密工具"></div>
        <div class="guide-dot" data-target="utf16-tool" data-label="UTF16转换"></div>
    </div>

    <div class="container">
        <!-- 主内容区 -->
        <div class="main-content">
            <!-- 加密工具部分 -->
            <div id="encrypt-tool" class="tool-section">
                <h2 class="section-title">加密工具（修复版-1.6.1.20250816.beta）</h2>

                <div class="input-group">
                    <select id="encryptShiftDirection" onchange="toggleEncryptSeedInput()">
                        <option value="after">向后移位（after）</option>
                        <option value="front">向前移位（front）</option>
                        <option value="mixed">混合模式（mixed）</option>
                    </select>
                    
                    <div id="encryptSeedInputGroup" class="hidden">
                        <input type="number" id="encryptSeedNumber" placeholder="种子数字（不填默认随机）">
                    </div>
                </div>

                <div class="input-group">
                    <input type="text" id="encryptShiftNumber" placeholder="数字（支持任意大的正整数）" required>
                    <span class="info">将按三位一组加密为英文单词</span>
                </div>

                <div class="input-group">
                    <input type="text" id="encryptContent" placeholder="内容（英文/拼音）" required>
                </div>

                <div class="input-group">
                    <select id="encryptSuffixType" onchange="toggleEncryptCustomSuffix()">
                        <option value="default">*rediron（默认）</option>
                        <option value="none">*无</option>
                        <option value="custom">*自定义</option>
                    </select>
                    <input type="text" id="encryptCustomSuffix" class="hidden" placeholder="尾标">
                </div>

                <div class="input-group">
                    <button onclick="generateEncryptResult()">生成加密结果</button>
                </div>

                <textarea id="encryptOutput" class="output-box" readonly placeholder="加密结果将显示在这里..."></textarea>
                
                <div class="note">
                    <p>加密说明：</p>
                    <p>1. 支持向后、向前和混合三种移位模式，混合模式需种子码</p>
                    <p>2. 数字按三位一组转换为英文，用随机无意义词分隔，内容中的数字将不转换</p>
                    <p>'</p>
                    <p>使用方式：将移位方式和移位数字与加密内容一并发送给好友，也可单独发送完仅双方知道的移位数字方式之后单独发送加密内容</p>
                    <p>'</p>
                    <p>注意：密文如果采用混合模式需要告诉好友种子码</p>
                </div>
            </div>

            <!-- 解密工具部分 -->
            <div id="decrypt-tool" class="tool-section">
                <h2 class="section-title">解密工具（修复版-2.16.1.20250816.beta）</h2>

                <!-- 解密模式切换 -->
                <div class="decrypt-mode-switch">
                    <label>
                        <input type="radio" name="decryptMode" value="normal" checked onclick="toggleDecryptMode()"> 
                        常规解密（已知参数）
                    </label>
                    <label style="margin-left: 20px;">
                        <input type="radio" name="decryptMode" value="smart" onclick="toggleDecryptMode()"> 
                        智能解密（未知参数）
                    </label>
                </div>

                <!-- 常规解密区域 -->
                <div id="normalDecryptArea">
                    <div class="input-group">
                        <select id="decryptShiftDirection" onchange="toggleDecryptSeedInput()">
                            <option value="after">对应加密：向后移位</option>
                            <option value="front">对应加密：向前移位</option>
                            <option value="mixed">对应加密：混合模式</option>
                        </select>
                        
                        <div id="decryptSeedInputGroup" class="hidden">
                            <input type="number" id="decryptSeedNumber" placeholder="必须输入加密时使用的种子">
                        </div>
                    </div>

                    <div class="input-group">
                        <input type="text" id="decryptShiftNumber" placeholder="输入加密时使用的移位数字" required>
                    </div>
                </div>

                <!-- 智能解密区域 -->
                <div id="smartDecryptArea" class="hidden">
                    <div class="input-group">
                        <div class="range-inputs">
                            <label>数字范围：从</label>
                            <input type="number" id="rangeStart" value="1" min="1" step="1">
                            <label>到</label>
                            <input type="number" id="rangeEnd" value="50" min="1" step="1">
                        </div>
                    </div>

                    <div class="input-group">
                        <input type="number" id="smartSeedInput" placeholder="种子（可选）">
                    </div>

                    <div class="input-group">
                        <label>
                            <input type="checkbox" id="tryAllSeeds" unchecked> 
                            尝试所有可能的种子
                        </label>
                        <span class="warning">注意：会非常耗时！</span>
                    </div>
                </div>

                <!-- 通用解密输入 -->
                <div class="input-group">
                    <input type="text" id="decryptContent" placeholder="输入（完整密文/内容密文）" required>
                </div>

                <div class="input-group">
                    <button onclick="generateDecryptResult()" class="primary">开始解密</button>
                    <button onclick="clearDecryptResults()" class="secondary">清空结果</button>
                </div>

                <!-- 解密输出 -->
                <div id="normalDecryptOutput">
                    <textarea id="decryptOutput" class="output-box" readonly placeholder="解密结果将显示在这里..."></textarea>
                    <div class="input-group" style="margin-top: 10px;">
                        <button onclick="secondaryDecrypt('normal')" class="tertiary">二次解密（转换数字格式）</button>
                    </div>
                    <div id="normalSecondaryResult" class="secondary-result hidden"></div>
                </div>

                <div id="smartDecryptOutput" class="hidden">
                    <div class="info">破解结果（仅显示首词为模式词的有效内容）：</div>
                    <div id="bruteForceResults" class="brute-force-results"></div>
                </div>
                
                <div class="note">
                    <p>功能说明：</p>
                    <p>1. 支持三种移位模式的加密和解密</p>
                    <p>2. 二次解密可将英文数字转换为阿拉伯数字</p>
                    <p>3. 智能解密可尝试破解未知参数的加密内容</p>
                </div>
            </div>

            <!-- UTF16互转功能 - 位于解密工具下方 -->
            <div id="utf16-tool" class="tool-section utf16-tool">
                <h2 class="section-title">UTF16编码/解码工具（3.4.1.20250817.alpha）</h2>
                
                <div class="input-group">
                    <textarea id="utf16Input" rows="6" placeholder="请输入需要转换的文本或UTF16编码..."></textarea>
                </div>
                
                <div class="input-group">
                    <button onclick="utf16Encode()" class="primary">文本 → UTF16编码</button>
                    <button onclick="utf16Decode()" class="secondary">UTF16编码 → 文本</button>
                </div>
                
                <div class="input-group">
                    <button onclick="clearUtf16()" class="tertiary">清空输入/输出</button>
                </div>
                
                <div class="input-group">
                    <textarea id="utf16Output" rows="6" class="output-box" readonly placeholder="转换结果将显示在这里..."></textarea>
                </div>
                
                <div class="note">
                    <p>UTF16转换说明：</p>
                    <p>1. 编码：将普通文本转换为\uXXXX格式的UTF16编码</p>
                    <p>2. 解码：将\uXXXX格式的UTF16编码转换回普通文本</p>
                    <p>3. 支持所有Unicode字符，包括中文、特殊符号等</p>
                </div>
            </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="side-content">
            <!-- 保持为空，作为主内容区的补充空间 -->
        </div>
    </div>

    <script>
        // 页面引导导航功能
        document.addEventListener('DOMContentLoaded', function() {
            const guideDots = document.querySelectorAll('.guide-dot');
            const sections = {
                'encrypt-tool': document.getElementById('encrypt-tool'),
                'decrypt-tool': document.getElementById('decrypt-tool'),
                'utf16-tool': document.getElementById('utf16-tool')
            };

            // 点击导航点滚动到对应区域
            guideDots.forEach(dot => {
                dot.addEventListener('click', function() {
                    const targetId = this.getAttribute('data-target');
                    if (sections[targetId]) {
                        sections[targetId].scrollIntoView({ behavior: 'smooth' });
                    }
                });
            });

            // 监听滚动，更新导航点状态
            window.addEventListener('scroll', function() {
                let activeSection = 'encrypt-tool'; // 默认第一个为激活状态
                const scrollPosition = window.scrollY + 100; // 加100px偏移

                // 检查哪个区域在当前视口中
                Object.keys(sections).forEach(sectionId => {
                    const section = sections[sectionId];
                    const sectionTop = section.offsetTop;
                    const sectionBottom = sectionTop + section.offsetHeight;

                    if (scrollPosition >= sectionTop && scrollPosition < sectionBottom) {
                        activeSection = sectionId;
                    }
                });

                // 更新导航点状态
                guideDots.forEach(dot => {
                    if (dot.getAttribute('data-target') === activeSection) {
                        dot.classList.add('active');
                    } else {
                        dot.classList.remove('active');
                    }
                });
            });
        });

        // 种子范围常量定义
        const MIN_SEED = -131072;
        const MAX_SEED = 131072;
        const SEED_RANGE = MAX_SEED - MIN_SEED + 1;

        // 无实际意义的分隔词列表（用于数字分组分隔）
        const separators = [
            "zap", "bix", "cun", "dov", "fep", 
            "gox", "huj", "kil", "myn", "nop",
            "qir", "sut", "vex", "wab", "xiz",
            "yot", "zar", "bek", "civ", "dum"
        ];

        // 加密格式关键词库
        const formatKeywords = ["front", "after", "mixed", "word", "rediron", "hundred", "and"];

        // 调整种子值到有效范围
        function adjustSeed(seed) {
            if (isNaN(seed)) return 0;
            let adjusted = ((seed - MIN_SEED) % SEED_RANGE + SEED_RANGE) % SEED_RANGE + MIN_SEED;
            return Math.round(adjusted);
        }

        // 切换解密模式
        function toggleDecryptMode() {
            const mode = document.querySelector('input[name="decryptMode"]:checked').value;
            document.getElementById('normalDecryptArea').classList.toggle('hidden', mode !== 'normal');
            document.getElementById('smartDecryptArea').classList.toggle('hidden', mode !== 'smart');
            document.getElementById('normalDecryptOutput').classList.toggle('hidden', mode !== 'normal');
            document.getElementById('smartDecryptOutput').classList.toggle('hidden', mode !== 'smart');
        }

        // 加密工具：显示/隐藏种子数输入框
        function toggleEncryptSeedInput() {
            const direction = document.getElementById('encryptShiftDirection').value;
            const seedInputGroup = document.getElementById('encryptSeedInputGroup');
            seedInputGroup.classList.toggle('hidden', direction !== 'mixed');
        }

        // 加密工具：显示/隐藏自定义尾标输入框
        function toggleEncryptCustomSuffix() {
            const suffixType = document.getElementById('encryptSuffixType').value;
            const customSuffix = document.getElementById('encryptCustomSuffix');
            customSuffix.classList.toggle('hidden', suffixType !== 'custom');
        }

        // 解密工具：显示/隐藏种子数输入框
        function toggleDecryptSeedInput() {
            const direction = document.getElementById('decryptShiftDirection').value;
            const seedInputGroup = document.getElementById('decryptSeedInputGroup');
            seedInputGroup.classList.toggle('hidden', direction !== 'mixed');
        }

        // 清空解密结果
        function clearDecryptResults() {
            document.getElementById('decryptOutput').value = '';
            document.getElementById('bruteForceResults').innerHTML = '';
            document.getElementById('normalSecondaryResult').classList.add('hidden');
        }

        // 提取有效加密内容
        function extractEncryptedContent(text) {
            const match = text.match(/([a-zA-Z\*\[ \]]+)$/);
            return match ? match[1].trim() : text.trim();
        }

        // 检查结果是否符合格式要求
        function isValidFormat(result) {
            if (!result.trim()) return false;
            const firstWord = result.trim().split(/\s+/)[0].toLowerCase();
            return ['front', 'after', 'mixed'].includes(firstWord);
        }

        // 伪随机数生成器（基于调整后的种子）
        function createPRNG(seed) {
            const adjustedSeed = adjustSeed(seed);
            return function() {
                let current = adjustedSeed;
                return function() {
                    current = (current * 9301 + 49297) % 233280;
                    return current / 233280;
                };
            }();
        }

        // 加密字符处理函数
        function encryptChar(char, shiftNum, direction, prng = null) {
            if (!/[a-zA-Z]/.test(char)) return char;

            let actualDirection = direction;
            if (direction === 'mixed' && prng) {
                actualDirection = prng() < 0.5 ? 'front' : 'after';
            }

            const base = char === char.toLowerCase() ? 97 : 65;
            const charCode = char.charCodeAt(0) - base + 1;

            let encryptedCode;
            const effectiveShift = Number(shiftNum % 26n);
            const actualShift = effectiveShift === 0 ? 26 : effectiveShift;

            if (actualDirection === 'after') {
                encryptedCode = charCode + actualShift;
                if (encryptedCode > 26) encryptedCode -= 26;
            } else {
                encryptedCode = charCode - actualShift;
                if (encryptedCode < 1) encryptedCode += 26;
            }

            return String.fromCharCode(encryptedCode + base - 1);
        }

        // 解密字符处理函数
        function decryptChar(char, shiftNum, direction, prng = null) {
            if (!/[a-zA-Z]/.test(char)) return char;

            let actualDirection = direction;
            if (direction === 'mixed' && prng) {
                actualDirection = prng() < 0.5 ? 'front' : 'after';
            }

            const base = char === char.toLowerCase() ? 97 : 65;
            const charCode = char.charCodeAt(0) - base + 1;

            let decryptedCode;
            const effectiveShift = Number(shiftNum % 26n);
            const actualShift = effectiveShift === 0 ? 26 : effectiveShift;

            if (actualDirection === 'after') {
                decryptedCode = charCode - actualShift;
                if (decryptedCode < 1) decryptedCode += 26;
            } else {
                decryptedCode = charCode + actualShift;
                if (decryptedCode > 26) decryptedCode -= 26;
            }

            return String.fromCharCode(decryptedCode + base - 1);
        }

        // 数字转英文（按三位一组，用随机分隔词分隔，支持负数）
        function numToWord(numStr) {
            const ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
                          "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
                          "seventeen", "eighteen", "nineteen"];
                          
            const tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
            
            // 处理小于1000的数字
            function convertLessThanOneThousand(n) {
                if (n === 0) return "";
                let res = "";
                const hundreds = Math.floor(n / 100);
                if (hundreds > 0) {
                    res += ones[hundreds] + " hundred";
                    n %= 100;
                    if (n > 0) res += " and ";
                }
                if (n < 20) {
                    res += ones[n];
                } else {
                    res += tens[Math.floor(n / 10)];
                    if (n % 10 !== 0) {
                        res += " " + ones[n % 10];
                    }
                }
                return res.trim();
            }
            
            // 将数字按三位一组拆分（从右向左）
            function splitNumberIntoGroups(numStr) {
                const groups = [];
                let isNegative = numStr.startsWith('-');
                let absNumStr = isNegative ? numStr.slice(1) : numStr;
                
                // 补零使长度为3的倍数
                if (absNumStr.length % 3 !== 0) {
                    absNumStr = '0'.repeat(3 - (absNumStr.length % 3)) + absNumStr;
                }
                
                // 按三位一组拆分
                for (let i = 0; i < absNumStr.length; i += 3) {
                    let group = absNumStr.slice(i, i + 3);
                    // 去除前导零但保留至少一位
                    group = group.replace(/^0+/, '') || '0';
                    groups.push(parseInt(group));
                }
                
                return { groups, isNegative };
            }
            
            // 特殊情况处理
            if (numStr === "0") return "zero";
            if (!/^-?\d+$/.test(numStr)) return "invalid number";
            
            const { groups, isNegative } = splitNumberIntoGroups(numStr);
            const groupWords = [];
            
            // 转换每个分组为英文
            groups.forEach(group => {
                if (group !== 0) {
                    groupWords.push(convertLessThanOneThousand(group));
                }
            });
            
            // 用随机分隔词连接分组
            let result = groupWords.join(` ${getRandomSeparator()} `);
            
            // 处理负数
            if (isNegative) {
                result = "negative " + result;
            }
            
            return result.trim();
        }

        // 英文数字转阿拉伯数字（匹配数字转英文的逻辑）
        function wordToNum(wordStr) {
            const wordValues = {
                "negative": -1,
                "zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
                "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,
                "eleven": 11, "twelve": 12, "thirteen": 13, "fourteen": 14,
                "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18,
                "nineteen": 19, "twenty": 20, "thirty": 30, "forty": 40,
                "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90,
                "hundred": 100
            };

            // 移除分隔词
            let cleanStr = wordStr;
            separators.forEach(sep => {
                cleanStr = cleanStr.replace(new RegExp(`\\b${sep}\\b`, 'gi'), ',');
            });

            // 按逗号分割分组
            const groups = cleanStr.split(',').map(g => g.trim()).filter(g => g);
            
            // 转换单个分组
            function convertGroup(group) {
                const words = group.toLowerCase().split(/\s+/);
                let num = 0;
                let current = 0;
                
                words.forEach(word => {
                    if (word === "and") return; // 忽略"and"
                    const val = wordValues[word];
                    if (val === 100) {
                        current *= val;
                    } else {
                        current += val;
                    }
                });
                
                return current;
            }
            
            // 转换所有分组并拼接
            const numGroups = groups.map(group => {
                const num = convertGroup(group);
                // 确保每个分组是3位数（补前导零）
                return num.toString().padStart(3, '0');
            });
            
            // 合并分组并处理负数
            let combined = numGroups.join('').replace(/^0+/, '');
            if (combined === '') combined = '0'; // 处理全零情况
            
            // 检查是否为负数
            if (wordStr.toLowerCase().includes('negative')) {
                combined = '-' + combined;
            }
            
            return BigInt(combined);
        }

        // 验证数字一致性
        function verifyNumberConsistency(inputNumStr, decryptedText) {
            // 1. 提取解密结果中的数字单词部分
            const parts = decryptedText.split(/\s+word\s+/);
            if (parts.length < 2) {
                return { valid: false, message: "移位数字异常请询问发送者。" };
            }
            
            const numWordPart = parts[0].split(/\s+/).slice(1).join(' '); // 移除模式词
            
            // 2. 转换输入数字为标准格式
            const inputNum = BigInt(inputNumStr);
            
            // 3. 转换解密结果中的数字单词为数字格式
            try {
                const convertedNum = wordToNum(numWordPart);
                // 4. 比较两种格式
                return convertedNum === inputNum
                    ? { valid: true, message: "数字验证通过" }
                    : { valid: false, message: "移位数字异常请询问发送者。" };
            } catch (e) {
                return { valid: false, message: "移位数字异常请询问发送者。" };
            }
        }

        // 获取随机分隔词
        function getRandomSeparator() {
            const randomIndex = Math.floor(Math.random() * separators.length);
            return separators[randomIndex];
        }

        // 生成加密结果
        function generateEncryptResult() {
            try {
                const direction = document.getElementById('encryptShiftDirection').value;
                const shiftNumStr = document.getElementById('encryptShiftNumber').value.trim();
                const content = document.getElementById('encryptContent').value.trim();
                const suffixType = document.getElementById('encryptSuffixType').value;
                let suffix = '';
                let seed = document.getElementById('encryptSeedNumber').value.trim();
                
                if (!/^\d+$/.test(shiftNumStr) || shiftNumStr === "0") {
                    alert('请输入有效的移位数字（仅数字，无其他字符）！');
                    return;
                }
                if (content === '') {
                    alert('请输入待加密的内容！');
                    return;
                }

                // 处理种子
                let seedUsed;
                if (direction === 'mixed') {
                    if (seed === '') {
                        // 随机生成在有效范围内的种子
                        seedUsed = Math.floor(Math.random() * SEED_RANGE) + MIN_SEED;
                    } else {
                        // 调整用户输入的种子到有效范围
                        seedUsed = adjustSeed(parseInt(seed));
                    }
                }

                if (suffixType === 'default') {
                    suffix = '*rediron';
                } else if (suffixType === 'custom') {
                    const customVal = document.getElementById('encryptCustomSuffix').value.trim();
                    suffix = customVal ? `*${customVal}` : '';
                } else {
                    suffix = '';
                }

                let prng = null;
                let seedWord = "";
                if (direction === 'mixed') {
                    seedWord = numToWord(seedUsed.toString());
                    prng = createPRNG(seedUsed);
                }

                const directionWord = direction === 'after' ? 'after' : 
                                     (direction === 'front' ? 'front' : 'mixed');
                const shiftWord = numToWord(shiftNumStr);
                let translatedBase = `${directionWord} ${shiftWord} word ${content}${suffix}`;
                const translated = direction === 'mixed' ? `${translatedBase}[${seedWord}]` : translatedBase;

                const shiftNum = BigInt(shiftNumStr);
                let encrypted = '';
                for (let i = 0; i < translated.length; i++) {
                    encrypted += encryptChar(translated[i], shiftNum, direction, prng);
                }

                let userInputDesc = `${direction === 'after' ? '后' : 
                                    (direction === 'front' ? '前' : '混合')}${shiftNumStr}个字`;
                if (direction === 'mixed') {
                    userInputDesc += `（种子：${seedUsed}）`;
                }
                
                const finalOutput = `（客户：${userInputDesc}，${content}${suffix ? suffix : ''}）\n（翻译后：${translated}）\n（加密后：${encrypted}）`;

                document.getElementById('encryptOutput').value = finalOutput;
            } catch (error) {
                alert('加密过程中出现错误：' + error.message);
                console.error(error);
            }
        }

        // 生成解密结果
        function generateDecryptResult() {
            const mode = document.querySelector('input[name="decryptMode"]:checked').value;
            const rawContent = document.getElementById('decryptContent').value.trim();
            if (!rawContent) {
                alert('请输入需要解密的内容！');
                return;
            }

            const encryptedContent = extractEncryptedContent(rawContent);

            if (mode === 'normal') {
                normalDecrypt(encryptedContent);
            } else {
                smartDecrypt(encryptedContent);
            }
        }

        // 常规解密
        function normalDecrypt(encryptedContent) {
            try {
                const direction = document.getElementById('decryptShiftDirection').value;
                const shiftNumStr = document.getElementById('decryptShiftNumber').value.trim();
                let seed = document.getElementById('decryptSeedNumber').value.trim();
                
                if (!/^\d+$/.test(shiftNumStr) || shiftNumStr === "0") {
                    alert('请输入有效的移位数字！');
                    return;
                }
                if (direction === 'mixed' && seed === '') {
                    alert('混合模式解密必须输入种子数！');
                    return;
                }

                // 调整种子到有效范围
                let adjustedSeed = null;
                if (direction === 'mixed') {
                    adjustedSeed = adjustSeed(parseInt(seed));
                }

                let prng = null;
                if (direction === 'mixed' && adjustedSeed !== null) {
                    prng = createPRNG(adjustedSeed);
                }

                const shiftNum = BigInt(shiftNumStr);
                let decrypted = '';
                for (let i = 0; i < encryptedContent.length; i++) {
                    decrypted += decryptChar(encryptedContent[i], shiftNum, direction, prng);
                }

                // 执行数字一致性检验
                const verification = verifyNumberConsistency(shiftNumStr, decrypted);
                
                // 不匹配时只输出提示信息
                let finalOutput;
                if (!verification.valid) {
                    finalOutput = verification.message; // 只输出异常提示
                } else {
                    // 匹配时正常输出完整信息
                    let resultDesc = `对应加密模式：${direction === 'after' ? '向后移位' : 
                                     (direction === 'front' ? '向前移位' : '混合模式')}，移位数字：${shiftNumStr}`;
                    if (direction === 'mixed') {
                        resultDesc += `，种子：${adjustedSeed}`;
                    }
                    finalOutput = `（解密参数：${resultDesc}）\n（解密内容：${encryptedContent}）\n（解密后：${decrypted}）\n${verification.message}`;
                }
                
                document.getElementById('decryptOutput').value = finalOutput;
                document.getElementById('normalSecondaryResult').classList.add('hidden');
                
                // 若检验失败，弹窗提示
                if (!verification.valid) {
                    alert(verification.message);
                }

            } catch (error) {
                alert('解密过程中出现错误：' + error.message);
                console.error(error);
            }
        }

        // 智能解密
        function smartDecrypt(encryptedContent) {
            try {
                const start = parseInt(document.getElementById('rangeStart').value);
                const end = parseInt(document.getElementById('rangeEnd').value);
                const customSeedInput = document.getElementById('smartSeedInput').value.trim();
                const tryAllSeeds = document.getElementById('tryAllSeeds').checked;
                const resultsContainer = document.getElementById('bruteForceResults');
                
                if (isNaN(start) || isNaN(end) || start < 1 || end < start) {
                    alert('请输入有效的数字范围（开始值≤结束值，且均为正整数）');
                    return;
                }
                
                // 警告用户全种子扫描的耗时
                if (tryAllSeeds && !confirm('尝试所有种子会非常耗时，可能导致浏览器无响应。是否继续？')) {
                    return;
                }
                
                resultsContainer.innerHTML = `正在破解（${start}-${end}），请稍候...`;

                const modes = ['after', 'front', 'mixed'];
                let results = [];

                // 确定要尝试的种子列表
                let seedsToTry = [];
                if (customSeedInput) {
                    const adjusted = adjustSeed(parseInt(customSeedInput));
                    seedsToTry = [adjusted];
                } else if (tryAllSeeds) {
                    for (let s = MIN_SEED; s <= MAX_SEED; s++) {
                        seedsToTry.push(s);
                    }
                } else {
                    for (let s = 0; s <= 100; s++) seedsToTry.push(s);
                    for (let s = -1; s >= -100; s--) seedsToTry.push(s);
                }

                // 显示当前尝试的种子数量
                resultsContainer.innerHTML = `正在破解（数字范围: ${start}-${end}，种子数量: ${seedsToTry.length}）...`;

                // 暴力尝试指定范围内的所有数字和种子
                let completed = 0;
                const total = (end - start + 1) * modes.length * seedsToTry.length;
                
                for (let num = start; num <= end; num++) {
                    for (const mode of modes) {
                        if (mode === 'mixed') {
                            for (const seed of seedsToTry) {
                                completed++;
                                if (completed % 100 === 0) {
                                    resultsContainer.innerHTML = 
                                        `正在破解（进度: ${Math.round(completed/total*100)}%）...`;
                                }
                                
                                const prng = createPRNG(seed);
                                let decrypted = '';
                                for (let i = 0; i < encryptedContent.length; i++) {
                                    decrypted += decryptChar(encryptedContent[i], BigInt(num), mode, prng);
                                }
                                if (isValidFormat(decrypted)) {
                                    const hasValidNumber = decrypted.includes('word') && 
                                                         decrypted.split('word')[0].split(/\s+/).length > 1;
                                    
                                    results.push({
                                        mode: mode,
                                        shiftNum: num,
                                        seed: seed,
                                        result: decrypted,
                                        score: getResultScore(decrypted) + (hasValidNumber ? 2 : 0)
                                    });
                                }
                            }
                        } else {
                            let decrypted = '';
                            for (let i = 0; i < encryptedContent.length; i++) {
                                decrypted += decryptChar(encryptedContent[i], BigInt(num), mode);
                            }
                            if (isValidFormat(decrypted)) {
                                const hasValidNumber = decrypted.includes('word') && 
                                                     decrypted.split('word')[0].split(/\s+/).length > 1;
                                
                                results.push({
                                    mode: mode,
                                    shiftNum: num,
                                    seed: '-',
                                    result: decrypted,
                                    score: getResultScore(decrypted) + (hasValidNumber ? 2 : 0)
                                });
                            }
                            completed++;
                        }
                    }
                }

                results.sort((a, b) => b.score - a.score);
                displayBruteForceResults(results);

            } catch (error) {
                alert('智能解密过程中出现错误：' + error.message);
                console.error(error);
            }
        }

        // 二次解密（转换数字格式）
        function secondaryDecrypt(mode) {
            let decryptedText;
            if (mode === 'normal') {
                const output = document.getElementById('decryptOutput').value;
                // 只处理验证通过的情况
                if (output.includes('数字验证通过')) {
                    const match = output.match(/（解密后：(.*?)）/s);
                    if (!match) {
                        alert('未找到可处理的解密结果');
                        return;
                    }
                    decryptedText = match[1];
                } else {
                    alert('请先获取验证通过的解密结果');
                    return;
                }
            } else if (mode === 'smart' && window.selectedSmartResult) {
                decryptedText = window.selectedSmartResult;
            } else {
                alert('请先完成解密并选择有效的结果');
                return;
            }

            try {
                let processed = decryptedText;
                
                // 提取模式词和数字部分
                const parts = processed.split(/\s+word\s+/);
                if (parts.length >= 2) {
                    const [modeAndNumPart, contentPart] = parts;
                    const [modeWord, ...numWords] = modeAndNumPart.split(/\s+/);
                    
                    // 转换数字部分
                    const numStr = numWords.join(' ');
                    const convertedNum = wordToNum(numStr);
                    processed = `${modeWord} ${convertedNum} word ${contentPart}`;
                }

                // 处理种子部分（如果有）
                if (processed.includes('[')) {
                    const seedMatch = processed.match(/\[([^\]]+)\]/);
                    if (seedMatch) {
                        const seedWords = seedMatch[1];
                        const convertedSeed = wordToNum(seedWords);
                        processed = processed.replace(`[${seedWords}]`, `[${convertedSeed}]`);
                    }
                }

                if (mode === 'normal') {
                    const resultEl = document.getElementById('normalSecondaryResult');
                    resultEl.innerHTML = `<strong>二次解密结果（数字已转换）：</strong><br>${processed}`;
                    resultEl.classList.remove('hidden');
                }
            } catch (e) {
                alert('二次解密失败：' + e.message);
                console.error(e);
            }
        }

        // 解密结果评分
        function getResultScore(text) {
            let score = 0;
            const words = text.toLowerCase().match(/[a-z]+/g) || [];
            words.forEach(word => {
                if (formatKeywords.includes(word)) {
                    score += 1;
                }
                if (word === 'word') {
                    score += 3;
                }
            });
            return score;
        }

        // 显示智能解密结果
        function displayBruteForceResults(results) {
            const container = document.getElementById('bruteForceResults');
            container.innerHTML = '';

            if (results.length === 0) {
                container.innerHTML = '未找到符合格式的解密结果（首词需为front/after/mixed）';
                return;
            }

            results.forEach((item, index) => {
                const resultDiv = document.createElement('div');
                resultDiv.className = `result-item ${item.score > 5 ? 'highlight' : ''}`;
                
                const modeText = item.mode === 'after' ? '向后' : (item.mode === 'front' ? '向前' : '混合');
                resultDiv.innerHTML = `
                    <strong>模式：${modeText}，数字：${item.shiftNum}${item.mode === 'mixed' ? `，种子：${item.seed}` : ''}</strong>
                    <div>结果：${item.result}</div>
                    <div class="input-group" style="margin-top: 5px; justify-content: flex-start;">
                        <button onclick="window.selectedSmartResult='${escapeHtml(item.result)}'; secondaryDecrypt('smart')" class="tertiary">
                            二次解密
                        </button>
                    </div>
                `;
                
                container.appendChild(resultDiv);
            });
        }

        // HTML转义
        function escapeHtml(text) {
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // UTF16编码函数
        function utf16Encode() {
            const input = document.getElementById('utf16Input').value.trim();
            if (!input) {
                alert('请输入需要编码的内容！');
                return;
            }
            
            let result = '';
            for (let i = 0; i < input.length; i++) {
                const code = input.charCodeAt(i).toString(16).toUpperCase();
                result += '\\u' + code.padStart(4, '0');
            }
            document.getElementById('utf16Output').value = result;
        }

        // UTF16解码函数
        function utf16Decode() {
            const input = document.getElementById('utf16Input').value.trim();
            if (!input) {
                alert('请输入需要解码的内容！');
                return;
            }
            
            try {
                // 处理\uXXXX格式的编码
                const result = input.replace(/\\u([0-9a-fA-F]{4})/g, (match, hex) => {
                    return String.fromCharCode(parseInt(hex, 16));
                });
                document.getElementById('utf16Output').value = result;
            } catch (error) {
                alert('解码失败：' + error.message);
                console.error(error);
            }
        }

        // 清空UTF16输入输出
        function clearUtf16() {
            document.getElementById('utf16Input').value = '';
            document.getElementById('utf16Output').value = '';
        }
    </script>
    <!-- 版权信息区域 -->
    <footer style="
margin: 50px auto 20px; 
padding-top: 20px; 
border-top: 1px solid #eee; 
max-width: 1400px; 
width: 95%; 
text-align: center; 
font-size: 14px;
background-color: #444; /* 灰黑色背景，可根据需求调整深浅 */
color: #fff; /* 文字颜色，搭配背景更清晰，可按需改 */
">
    <p>© [2025] [红铁工作室] 保留所有权利</p>
    <p>Version：v3.4.7.20250817.release</p>
    <p style="margin: 5px 0;">bug联系方式：[3603903466]</p>
    <p style="margin: 5px 0;">[沪RISCP备Tools2025081601号]</p>
    <p style="margin: 5px 0; font-size: 12px;">[红铁工作室_狼腹负责主要研发]</p>
    <p style="margin: 5px 0;">RISCP全称为RedIron Studio Content Private非商用红铁工作室内容提供商</p>
</footer>
</body>
</html>
